Learn UML: States and Transitions

In Object-Oriented Modeling, State Machine Diagrams describe how an object changes over its lifespan in response to events. This tutorial covers the fundamental building blocks: States and Transitions.

Key Takeaway:

1. The Anatomy of a State

In UML, a state is rendered as a rounded rectangle. It is divided into compartments to show the state's name and internal activities.

ActiveState entry / initialize() do / processData() exit / cleanup()
Figure 1: Standard UML State representation with internal activity compartments

Internal Activities Explained:

Activity Type Trigger Moment Description
entry / action On Entering Executes immediately when the object enters the state. Cannot be interrupted.
do / activity While In State An ongoing behavior performed while the object remains in the state. Can be interrupted by transitions.
exit / action On Exiting Executes immediately before the object leaves the state. Cannot be interrupted.

2. Anatomy of a Transition

A transition is represented as a solid directed line connecting a source state to a target state.

State A Event(args) [Guard Condition] / Action() State B
Figure 2: Formal UML Transition Syntax String

Transition Syntax Breakdown:

1. Event Name

The trigger that fires the transition (e.g., buttonClicked or tempChanged).

2. [ Guard Condition ]

A Boolean expression enclosed in square brackets. The transition only fires if this evaluates to true.

3. / Action

An executable atomic calculation or operation executed during the state shift.

3. Practical Domain Examples

Below are detailed UML state machine examples modeling real-world dynamic behavior.

Example A: Chess Game Lifecycle

This diagram models the turn-taking flow in a chess game, handling checks, checkmates, and draws.

WhiteToMove do / waitWhiteInput() movePiece() [!isCheckmate && !isDraw] movePiece() [!isCheckmate && !isDraw] BlackToMove do / waitBlackInput() movePiece() [isCheckmate || isDraw] movePiece() [isCheckmate || isDraw] GameOver
Figure 3: State machine diagram for a Turn-Based Chess Game Engine

Example B: Landline Telephone System

This traditional UML state model demonstrates state switches during a phone call lifecycle based on user actions and network responses.

Idle (On Hook) liftReceiver() Dial Tone do / playTone() dialDigit(n) Ringing do / ringCallee() calleeAnswers() Connected do / startVoiceChannel() hangUp() / disconnect() after (15 sec) Busy Tone hangUp()
Figure 4: Complete State Machine for a Landline Phone System